var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var miaoRouter = require('./routes/miao')
var answerRouter = require('./routes/answer')
var userRouter = require('./routes/user')

var app = express();

// 解决跨域
//解决跨域问题
app.all('*',function (req, res, next) {
    // 允许哪一个远程地址访问  所有的地址都可以访问(安全性低)
    res.header('Access-Control-Allow-Origin','*'); //当允许携带cookies此处的白名单不能写’*’
    // 允许的请求头
    res.header('Access-Control-Allow-Headers','content-type,token,Content-Length, Authorization,Origin,Accept,X-Requested-With'); //允许的请求头
    // 允许请求的方法
    res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT'); //允许的请求方法
    // 允许携带cookie
    res.header('Access-Control-Allow-Credentials',true);  //允许携带cookies
    // 往下走
    next();
  });

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/miao',miaoRouter)
app.use('/answer',answerRouter)
app.use("/user",userRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
}); 

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
